// pages/launcher/launcher.js
var app = getApp()

Page({
  data: {
    top: 80,
    isHidden: true,
  },

  login: function (code) {
    var that = this;
    wx.request({
      url: getApp().globalData.HTTP + '/asf/usercenter/user/regist',
      data: {
        code: code,
      },
      method: 'POST',
      success: function (res) {
        console.log('开发者服务器登陆', res, code)
        if (res.statusCode == 200) {
          getApp().globalData.token = res.data.accessToken;
          wx.reLaunch({
            url: '/pages/index/index',
          })
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
          })
          wx.showModal({
            title: '提示',
            content: '登录失败，请重试',
            showCancel: true,
            cancelText: '退出',
            cancelColor: '',
            confirmText: '重试',
            confirmColor: '',
            success: function (res) {
              if (res.confirm) {
                that.login(code)
              } else if (res.cancel) {
                wx.navigateBack({
                  delta: 0
                })
              }
            },
            fail: function (res) {
            },
            complete: function (res) { },
          })
        }
      },
      fail: function (res) {
        console.log('res1', res)
        setTimeout(function () {
          that.login(code)
        }, 3000)
      },
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.wxLogin()
  },

  // 获取用户授权
  getUserAuthor() {
    wx.getSetting({
      success (res) {
        console.log(res.authSetting)
        // res.authSetting = {
        //   "scope.userInfo": true,
        //   "scope.userLocation": true
        // }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // console.log('启动...')
    // this.wxLogin()
  },

  wxLogin() {
    var that = this
    setTimeout(function () {
      wx.login({
        success: res => {
          console.log('微信登录', res)
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          if (res.code) {
            //发起网络请求
            that.login(res.code)
          } else {
            setTimeout(function () {
              that.wxLogin()
            }, 2000)
          }
        },
        fail: res => {
          setTimeout(function () {
            that.wxLogin()
          }, 2000)
        }
      })
    }, 2000) 
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})